using System.Web.Mvc;
using Kiwi.Container.Application;
using Kiwi.Container.DependencyInjection;

namespace Kiwi.Container.Web.Mvc
{
    public class DependencyInjectingViewEngine : IViewEngine
    {
        private readonly IViewEngine _viewEngine;
        private readonly IEnumerateDependentProperties _dependentProperties;

        public DependencyInjectingViewEngine(IViewEngine viewEngine, IEnumerateDependentProperties dependentProperties)
        {
            _viewEngine = viewEngine;
            _dependentProperties = dependentProperties;
        }

        #region IViewEngine Members

        public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName,
                                                bool useCache)
        {
            return Inject(_viewEngine.FindPartialView(controllerContext, partialViewName, useCache));
        }

        public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName,
                                         bool useCache)
        {
            return Inject(_viewEngine.FindView(controllerContext, viewName, masterName, useCache));
        }

        public void ReleaseView(ControllerContext controllerContext, IView view)
        {
            _viewEngine.ReleaseView(controllerContext, view);
        }

        #endregion

        private ViewEngineResult Inject(ViewEngineResult result)
        {
            if ((result != null) && (result.View != null))
            {
                ContainerManager.Current.Inject(result.View, _dependentProperties);
                return new ViewEngineResult(result.View, this);
            }
            return result;
        }
    }
}